package com.syjy.tunnelworker.workassist.iec104tcp;


import com.syjy.container.ProtocolDataContainer;
import com.syjy.tunnelinfo.DataPoint;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import wei.yigulu.iec104.annotation.AsduType;
import wei.yigulu.iec104.apdumodel.Apdu;
import wei.yigulu.iec104.asdudataframe.NormalizedIntegerType;
import wei.yigulu.iec104.asdudataframe.qualitydescription.IeMeasuredQuality;
import wei.yigulu.iec104.asdudataframe.typemodel.InformationBodyAddress;
import wei.yigulu.iec104.nettyconfig.Iec104HSMasterBuilder;
import wei.yigulu.netty.BaseProtocolBuilder;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 没有品质位的归一化值
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@EqualsAndHashCode(callSuper = true)
@AsduType(typeId = 9)
@Data
@NoArgsConstructor
public class HandelNormalizedInteger extends NormalizedIntegerType {


	private ProtocolDataContainer protocolDataContainer = ProtocolDataContainer.getInstance();


	@Override
	public byte[][] handleAndAnswer(Apdu apdu) throws Exception {
		apdu.getLog().trace("----------处理的归一化值数据---------");
		BaseProtocolBuilder builder = apdu.getIec104Builder();
		if (builder != null && builder instanceof Iec104HSMasterBuilder) {
			//所有master 视为统一的 处理逻辑---存入数据池
			Map<Integer, DataPoint> dataPoint = (Map<Integer, DataPoint>) builder.getConfigInfoMap().get("104DataPoint");
			HandelNormalizedInteger handelNoQualityInt = (HandelNormalizedInteger) apdu.getAsdu().getDataFrame();
			List<InformationBodyAddress> address = handelNoQualityInt.getAddresses();
			Map<IeMeasuredQuality, Integer> datas = handelNoQualityInt.getDatas();
			int i = 0;
			//存入共享服务端
			if (apdu.getAsdu().getVsq().getSq() == 0) {
				apdu.getLog().trace("------处理归一化值单一寻址-----");
				for (Map.Entry<IeMeasuredQuality, Integer> e : datas.entrySet()) {
					if (dataPoint.containsKey(address.get(i).getAddress())) {
						protocolDataContainer.putNumber(dataPoint.get(address.get(i).getAddress()).getId(), BigDecimal.valueOf(e.getValue()).multiply(BigDecimal.valueOf(dataPoint.get(address.get(i).getAddress()).getMag())));
					}
					i++;
				}
			} else if (apdu.getAsdu().getVsq().getSq() == 1) {
				apdu.getLog().trace("------处理归一化值连续寻址-----");
				i = address.get(0).getAddress();
				for (Map.Entry<IeMeasuredQuality, Integer> e : datas.entrySet()) {
					if (dataPoint.containsKey(i)) {
						protocolDataContainer.putNumber(dataPoint.get(i).getId(), BigDecimal.valueOf(e.getValue()).multiply(BigDecimal.valueOf(dataPoint.get(i).getMag())));
					}
					i++;
				}
			}
		}
		return null;
	}


	@Override
	public String toString() {
		return super.toString();
	}


}
